home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / httplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  34KB  |  1,163 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''HTTP/1.1 client library
  5.  
  6. <intro stuff goes here>
  7. <other stuff, too>
  8.  
  9. HTTPConnection goes through a number of "states", which define when a client
  10. may legally make another request or fetch the response for a particular
  11. request. This diagram details these state transitions:
  12.  
  13.     (null)
  14.       |
  15.       | HTTPConnection()
  16.       v
  17.     Idle
  18.       |
  19.       | putrequest()
  20.       v
  21.     Request-started
  22.       |
  23.       | ( putheader() )*  endheaders()
  24.       v
  25.     Request-sent
  26.       |
  27.       | response = getresponse()
  28.       v
  29.     Unread-response   [Response-headers-read]
  30.       |\\____________________
  31.       |                     |
  32.       | response.read()     | putrequest()
  33.       v                     v
  34.     Idle                  Req-started-unread-response
  35.                      ______/|
  36.                    /        |
  37.    response.read() |        | ( putheader() )*  endheaders()
  38.                    v        v
  39.        Request-started    Req-sent-unread-response
  40.                             |
  41.                             | response.read()
  42.                             v
  43.                           Request-sent
  44.  
  45. This diagram presents the following rules:
  46.   -- a second request may not be started until {response-headers-read}
  47.   -- a response [object] cannot be retrieved until {request-sent}
  48.   -- there is no differentiation between an unread response body and a
  49.      partially read response body
  50.  
  51. Note: this enforcement is applied by the HTTPConnection class. The
  52.       HTTPResponse class does not enforce this state machine, which
  53.       implies sophisticated clients may accelerate the request/response
  54.       pipeline. Caution should be taken, though: accelerating the states
  55.       beyond the above pattern may imply knowledge of the server\'s
  56.       connection-close behavior for certain requests. For example, it
  57.       is impossible to tell whether the server will close the connection
  58.       UNTIL the response headers have been read; this means that further
  59.       requests cannot be placed into the pipeline until it is known that
  60.       the server will NOT be closing the connection.
  61.  
  62. Logical State                  __state            __response
  63. -------------                  -------            ----------
  64. Idle                           _CS_IDLE           None
  65. Request-started                _CS_REQ_STARTED    None
  66. Request-sent                   _CS_REQ_SENT       None
  67. Unread-response                _CS_IDLE           <response_class>
  68. Req-started-unread-response    _CS_REQ_STARTED    <response_class>
  69. Req-sent-unread-response       _CS_REQ_SENT       <response_class>
  70. '''
  71. from array import array
  72. import os
  73. import socket
  74. from sys import py3kwarning
  75. from urlparse import urlsplit
  76. import warnings
  77. with warnings.catch_warnings():
  78.     if py3kwarning:
  79.         warnings.filterwarnings('ignore', '.*mimetools has been removed', DeprecationWarning)
  80.     import mimetools
  81.  
  82. try:
  83.     from cStringIO import StringIO
  84. except ImportError:
  85.     from StringIO import StringIO
  86.  
  87. __all__ = [
  88.     'HTTP',
  89.     'HTTPResponse',
  90.     'HTTPConnection',
  91.     'HTTPException',
  92.     'NotConnected',
  93.     'UnknownProtocol',
  94.     'UnknownTransferEncoding',
  95.     'UnimplementedFileMode',
  96.     'IncompleteRead',
  97.     'InvalidURL',
  98.     'ImproperConnectionState',
  99.     'CannotSendRequest',
  100.     'CannotSendHeader',
  101.     'ResponseNotReady',
  102.     'BadStatusLine',
  103.     'error',
  104.     'responses']
  105. HTTP_PORT = 80
  106. HTTPS_PORT = 443
  107. _UNKNOWN = 'UNKNOWN'
  108. _CS_IDLE = 'Idle'
  109. _CS_REQ_STARTED = 'Request-started'
  110. _CS_REQ_SENT = 'Request-sent'
  111. CONTINUE = 100
  112. SWITCHING_PROTOCOLS = 101
  113. PROCESSING = 102
  114. OK = 200
  115. CREATED = 201
  116. ACCEPTED = 202
  117. NON_AUTHORITATIVE_INFORMATION = 203
  118. NO_CONTENT = 204
  119. RESET_CONTENT = 205
  120. PARTIAL_CONTENT = 206
  121. MULTI_STATUS = 207
  122. IM_USED = 226
  123. MULTIPLE_CHOICES = 300
  124. MOVED_PERMANENTLY = 301
  125. FOUND = 302
  126. SEE_OTHER = 303
  127. NOT_MODIFIED = 304
  128. USE_PROXY = 305
  129. TEMPORARY_REDIRECT = 307
  130. BAD_REQUEST = 400
  131. UNAUTHORIZED = 401
  132. PAYMENT_REQUIRED = 402
  133. FORBIDDEN = 403
  134. NOT_FOUND = 404
  135. METHOD_NOT_ALLOWED = 405
  136. NOT_ACCEPTABLE = 406
  137. PROXY_AUTHENTICATION_REQUIRED = 407
  138. REQUEST_TIMEOUT = 408
  139. CONFLICT = 409
  140. GONE = 410
  141. LENGTH_REQUIRED = 411
  142. PRECONDITION_FAILED = 412
  143. REQUEST_ENTITY_TOO_LARGE = 413
  144. REQUEST_URI_TOO_LONG = 414
  145. UNSUPPORTED_MEDIA_TYPE = 415
  146. REQUESTED_RANGE_NOT_SATISFIABLE = 416
  147. EXPECTATION_FAILED = 417
  148. UNPROCESSABLE_ENTITY = 422
  149. LOCKED = 423
  150. FAILED_DEPENDENCY = 424
  151. UPGRADE_REQUIRED = 426
  152. INTERNAL_SERVER_ERROR = 500
  153. NOT_IMPLEMENTED = 501
  154. BAD_GATEWAY = 502
  155. SERVICE_UNAVAILABLE = 503
  156. GATEWAY_TIMEOUT = 504
  157. HTTP_VERSION_NOT_SUPPORTED = 505
  158. INSUFFICIENT_STORAGE = 507
  159. NOT_EXTENDED = 510
  160. responses = {
  161.     100: 'Continue',
  162.     101: 'Switching Protocols',
  163.     200: 'OK',
  164.     201: 'Created',
  165.     202: 'Accepted',
  166.     203: 'Non-Authoritative Information',
  167.     204: 'No Content',
  168.     205: 'Reset Content',
  169.     206: 'Partial Content',
  170.     300: 'Multiple Choices',
  171.     301: 'Moved Permanently',
  172.     302: 'Found',
  173.     303: 'See Other',
  174.     304: 'Not Modified',
  175.     305: 'Use Proxy',
  176.     306: '(Unused)',
  177.     307: 'Temporary Redirect',
  178.     400: 'Bad Request',
  179.     401: 'Unauthorized',
  180.     402: 'Payment Required',
  181.     403: 'Forbidden',
  182.     404: 'Not Found',
  183.     405: 'Method Not Allowed',
  184.     406: 'Not Acceptable',
  185.     407: 'Proxy Authentication Required',
  186.     408: 'Request Timeout',
  187.     409: 'Conflict',
  188.     410: 'Gone',
  189.     411: 'Length Required',
  190.     412: 'Precondition Failed',
  191.     413: 'Request Entity Too Large',
  192.     414: 'Request-URI Too Long',
  193.     415: 'Unsupported Media Type',
  194.     416: 'Requested Range Not Satisfiable',
  195.     417: 'Expectation Failed',
  196.     500: 'Internal Server Error',
  197.     501: 'Not Implemented',
  198.     502: 'Bad Gateway',
  199.     503: 'Service Unavailable',
  200.     504: 'Gateway Timeout',
  201.     505: 'HTTP Version Not Supported' }
  202. MAXAMOUNT = 1048576
  203. _MAXLINE = 65536
  204.  
  205. class HTTPMessage(mimetools.Message):
  206.     
  207.     def addheader(self, key, value):
  208.         '''Add header for field key handling repeats.'''
  209.         prev = self.dict.get(key)
  210.         if prev is None:
  211.             self.dict[key] = value
  212.         else:
  213.             combined = ', '.join((prev, value))
  214.             self.dict[key] = combined
  215.  
  216.     
  217.     def addcontinue(self, key, more):
  218.         '''Add more field data from a continuation line.'''
  219.         prev = self.dict[key]
  220.         self.dict[key] = prev + '\n ' + more
  221.  
  222.     
  223.     def readheaders(self):
  224.         '''Read header lines.
  225.  
  226.         Read header lines up to the entirely blank line that terminates them.
  227.         The (normally blank) line that ends the headers is skipped, but not
  228.         included in the returned list.  If a non-header line ends the headers,
  229.         (which is an error), an attempt is made to backspace over it; it is
  230.         never included in the returned list.
  231.  
  232.         The variable self.status is set to the empty string if all went well,
  233.         otherwise it is an error message.  The variable self.headers is a
  234.         completely uninterpreted list of lines contained in the header (so
  235.         printing them will reproduce the header exactly as it appears in the
  236.         file).
  237.  
  238.         If multiple header fields with the same name occur, they are combined
  239.         according to the rules in RFC 2616 sec 4.2:
  240.  
  241.         Appending each subsequent field-value to the first, each separated
  242.         by a comma. The order in which header fields with the same field-name
  243.         are received is significant to the interpretation of the combined
  244.         field value.
  245.         '''
  246.         self.dict = { }
  247.         self.unixfrom = ''
  248.         self.headers = hlist = []
  249.         self.status = ''
  250.         headerseen = ''
  251.         firstline = 1
  252.         startofline = None
  253.         unread = None
  254.         tell = None
  255.         if hasattr(self.fp, 'unread'):
  256.             unread = self.fp.unread
  257.         elif self.seekable:
  258.             tell = self.fp.tell
  259.         while True:
  260.             if tell:
  261.                 
  262.                 try:
  263.                     startofline = tell()
  264.                 except IOError:
  265.                     startofline = None
  266.                     tell = None
  267.                     self.seekable = 0
  268.                 
  269.  
  270.             line = self.fp.readline(_MAXLINE + 1)
  271.             if len(line) > _MAXLINE:
  272.                 raise LineTooLong('header line')
  273.             if not line:
  274.                 self.status = 'EOF in headers'
  275.                 break
  276.             if firstline and line.startswith('From '):
  277.                 self.unixfrom = self.unixfrom + line
  278.                 continue
  279.             firstline = 0
  280.             if headerseen and line[0] in ' \t':
  281.                 hlist.append(line)
  282.                 self.addcontinue(headerseen, line.strip())
  283.                 continue
  284.             elif self.iscomment(line):
  285.                 continue
  286.             elif self.islast(line):
  287.                 break
  288.             headerseen = self.isheader(line)
  289.             if headerseen:
  290.                 hlist.append(line)
  291.                 self.addheader(headerseen, line[len(headerseen) + 1:].strip())
  292.                 continue
  293.                 continue
  294.             if not self.dict:
  295.                 self.status = 'No headers'
  296.             else:
  297.                 self.status = 'Non-header line where header expected'
  298.             if unread:
  299.                 unread(line)
  300.             elif tell:
  301.                 self.fp.seek(startofline)
  302.             else:
  303.                 self.status = self.status + '; bad seek'
  304.             break
  305.  
  306.  
  307.  
  308. class HTTPResponse:
  309.     
  310.     def __init__(self, sock, debuglevel = 0, strict = 0, method = None, buffering = False):
  311.         if buffering:
  312.             self.fp = sock.makefile('rb')
  313.         else:
  314.             self.fp = sock.makefile('rb', 0)
  315.         self.debuglevel = debuglevel
  316.         self.strict = strict
  317.         self._method = method
  318.         self.msg = None
  319.         self.version = _UNKNOWN
  320.         self.status = _UNKNOWN
  321.         self.reason = _UNKNOWN
  322.         self.chunked = _UNKNOWN
  323.         self.chunk_left = _UNKNOWN
  324.         self.length = _UNKNOWN
  325.         self.will_close = _UNKNOWN
  326.  
  327.     
  328.     def _read_status(self):
  329.         line = self.fp.readline(_MAXLINE + 1)
  330.         if len(line) > _MAXLINE:
  331.             raise LineTooLong('header line')
  332.         if self.debuglevel > 0:
  333.             print 'reply:', repr(line)
  334.         if not line:
  335.             raise BadStatusLine(line)
  336.         
  337.         try:
  338.             (version, status, reason) = line.split(None, 2)
  339.         except ValueError:
  340.             
  341.             try:
  342.                 (version, status) = line.split(None, 1)
  343.                 reason = ''
  344.             except ValueError:
  345.                 version = ''
  346.             
  347.  
  348.  
  349.         if not version.startswith('HTTP/'):
  350.             if self.strict:
  351.                 self.close()
  352.                 raise BadStatusLine(line)
  353.             self.fp = LineAndFileWrapper(line, self.fp)
  354.             return ('HTTP/0.9', 200, '')
  355.         
  356.         try:
  357.             status = int(status)
  358.             if status < 100 or status > 999:
  359.                 raise BadStatusLine(line)
  360.         except ValueError:
  361.             raise BadStatusLine(line)
  362.  
  363.         return (version, status, reason)
  364.  
  365.     
  366.     def begin(self):
  367.         if self.msg is not None:
  368.             return None
  369.         if True:
  370.             (version, status, reason) = self._read_status()
  371.             if status != CONTINUE:
  372.                 break
  373.             while True:
  374.                 skip = self.fp.readline(_MAXLINE + 1)
  375.                 if len(skip) > _MAXLINE:
  376.                     raise LineTooLong('header line')
  377.                 skip = skip.strip()
  378.                 if not skip:
  379.                     break
  380.                 if self.debuglevel > 0:
  381.                     print 'header:', skip
  382.                     continue
  383.             self.status = status
  384.             self.reason = reason.strip()
  385.             if version == 'HTTP/1.0':
  386.                 self.version = 10
  387.             elif version.startswith('HTTP/1.'):
  388.                 self.version = 11
  389.             elif version == 'HTTP/0.9':
  390.                 self.version = 9
  391.             else:
  392.                 raise UnknownProtocol(version)
  393.             if None.version == 9:
  394.                 self.length = None
  395.                 self.chunked = 0
  396.                 self.will_close = 1
  397.                 self.msg = HTTPMessage(StringIO())
  398.                 return None
  399.             self.msg = None(self.fp, 0)
  400.             if self.debuglevel > 0:
  401.                 for hdr in self.msg.headers:
  402.                     print 'header:', hdr,
  403.                 
  404.             self.msg.fp = None
  405.             tr_enc = self.msg.getheader('transfer-encoding')
  406.             if tr_enc and tr_enc.lower() == 'chunked':
  407.                 self.chunked = 1
  408.                 self.chunk_left = None
  409.             else:
  410.                 self.chunked = 0
  411.         self.will_close = self._check_close()
  412.         length = self.msg.getheader('content-length')
  413.         if length and not (self.chunked):
  414.             
  415.             try:
  416.                 self.length = int(length)
  417.             except ValueError:
  418.                 self.length = None
  419.  
  420.             if self.length < 0:
  421.                 self.length = None
  422.             
  423.         else:
  424.             self.length = None
  425.         if not status == NO_CONTENT and status == NOT_MODIFIED:
  426.             if status <= status:
  427.                 pass
  428.             elif status < 200 or self._method == 'HEAD':
  429.                 self.length = 0
  430.             if not (self.will_close) and not (self.chunked) and self.length is None:
  431.                 self.will_close = 1
  432.             return None
  433.  
  434.     
  435.     def _check_close(self):
  436.         conn = self.msg.getheader('connection')
  437.         if self.version == 11:
  438.             conn = self.msg.getheader('connection')
  439.             if conn and 'close' in conn.lower():
  440.                 return True
  441.             return None
  442.         if None.msg.getheader('keep-alive'):
  443.             return False
  444.         if None and 'keep-alive' in conn.lower():
  445.             return False
  446.         pconn = None.msg.getheader('proxy-connection')
  447.         if pconn and 'keep-alive' in pconn.lower():
  448.             return False
  449.  
  450.     
  451.     def close(self):
  452.         if self.fp:
  453.             self.fp.close()
  454.             self.fp = None
  455.  
  456.     
  457.     def isclosed(self):
  458.         return self.fp is None
  459.  
  460.     
  461.     def read(self, amt = None):
  462.         if self.fp is None:
  463.             return ''
  464.         if None._method == 'HEAD':
  465.             self.close()
  466.             return ''
  467.         if None.chunked:
  468.             return self._read_chunked(amt)
  469.         if None is None:
  470.             if self.length is None:
  471.                 s = self.fp.read()
  472.             else:
  473.                 
  474.                 try:
  475.                     s = self._safe_read(self.length)
  476.                 except IncompleteRead:
  477.                     self.close()
  478.                     raise 
  479.  
  480.                 self.length = 0
  481.             self.close()
  482.             return s
  483.         if None.length is not None and amt > self.length:
  484.             amt = self.length
  485.         
  486.         s = self.fp.read(amt)
  487.         if not s:
  488.             self.close()
  489.         if self.length is not None:
  490.             self.length -= len(s)
  491.             if not self.length:
  492.                 self.close()
  493.             
  494.         return s
  495.  
  496.     
  497.     def _read_chunked(self, amt):
  498.         if not self.chunked != _UNKNOWN:
  499.             raise AssertionError
  500.         chunk_left = None.chunk_left
  501.         value = []
  502.         while True:
  503.             if chunk_left is None:
  504.                 line = self.fp.readline(_MAXLINE + 1)
  505.                 if len(line) > _MAXLINE:
  506.                     raise LineTooLong('chunk size')
  507.                 i = line.find(';')
  508.                 if i >= 0:
  509.                     line = line[:i]
  510.                 
  511.                 try:
  512.                     chunk_left = int(line, 16)
  513.                 except ValueError:
  514.                     self.close()
  515.                     raise IncompleteRead(''.join(value))
  516.  
  517.                 if chunk_left == 0:
  518.                     break
  519.                 
  520.             if amt is None:
  521.                 value.append(self._safe_read(chunk_left))
  522.             elif amt < chunk_left:
  523.                 value.append(self._safe_read(amt))
  524.                 self.chunk_left = chunk_left - amt
  525.                 return ''.join(value)
  526.             if amt == chunk_left:
  527.                 value.append(self._safe_read(amt))
  528.                 self._safe_read(2)
  529.                 self.chunk_left = None
  530.                 return ''.join(value)
  531.             None.append(self._safe_read(chunk_left))
  532.             amt -= chunk_left
  533.             self._safe_read(2)
  534.             chunk_left = None
  535.         while True:
  536.             line = self.fp.readline(_MAXLINE + 1)
  537.             if len(line) > _MAXLINE:
  538.                 raise LineTooLong('trailer line')
  539.             if not line:
  540.                 break
  541.             if line == '\r\n':
  542.                 break
  543.                 continue
  544.             self.close()
  545.             return ''.join(value)
  546.  
  547.     
  548.     def _safe_read(self, amt):
  549.         '''Read the number of bytes requested, compensating for partial reads.
  550.  
  551.         Normally, we have a blocking socket, but a read() can be interrupted
  552.         by a signal (resulting in a partial read).
  553.  
  554.         Note that we cannot distinguish between EOF and an interrupt when zero
  555.         bytes have been read. IncompleteRead() will be raised in this
  556.         situation.
  557.  
  558.         This function should be used when <amt> bytes "should" be present for
  559.         reading. If the bytes are truly not available (due to EOF), then the
  560.         IncompleteRead exception can be used to detect the problem.
  561.         '''
  562.         s = []
  563.         while amt > 0:
  564.             chunk = self.fp.read(min(amt, MAXAMOUNT))
  565.             if not chunk:
  566.                 raise IncompleteRead(''.join(s), amt)
  567.             s.append(chunk)
  568.             amt -= len(chunk)
  569.         return ''.join(s)
  570.  
  571.     
  572.     def fileno(self):
  573.         return self.fp.fileno()
  574.  
  575.     
  576.     def getheader(self, name, default = None):
  577.         if self.msg is None:
  578.             raise ResponseNotReady()
  579.         return self.msg.getheader(name, default)
  580.  
  581.     
  582.     def getheaders(self):
  583.         '''Return list of (header, value) tuples.'''
  584.         if self.msg is None:
  585.             raise ResponseNotReady()
  586.         return self.msg.items()
  587.  
  588.  
  589.  
  590. class HTTPConnection:
  591.     _http_vsn = 11
  592.     _http_vsn_str = 'HTTP/1.1'
  593.     response_class = HTTPResponse
  594.     default_port = HTTP_PORT
  595.     auto_open = 1
  596.     debuglevel = 0
  597.     strict = 0
  598.     
  599.     def __init__(self, host, port = None, strict = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT, source_address = None):
  600.         self.timeout = timeout
  601.         self.source_address = source_address
  602.         self.sock = None
  603.         self._buffer = []
  604.         self._HTTPConnection__response = None
  605.         self._HTTPConnection__state = _CS_IDLE
  606.         self._method = None
  607.         self._tunnel_host = None
  608.         self._tunnel_port = None
  609.         self._tunnel_headers = { }
  610.         self._set_hostport(host, port)
  611.         if strict is not None:
  612.             self.strict = strict
  613.  
  614.     
  615.     def set_tunnel(self, host, port = None, headers = None):
  616.         ''' Sets up the host and the port for the HTTP CONNECT Tunnelling.
  617.  
  618.         The headers argument should be a mapping of extra HTTP headers
  619.         to send with the CONNECT request.
  620.         '''
  621.         self._tunnel_host = host
  622.         self._tunnel_port = port
  623.         if headers:
  624.             self._tunnel_headers = headers
  625.         else:
  626.             self._tunnel_headers.clear()
  627.  
  628.     
  629.     def _set_hostport(self, host, port):
  630.         if port is None:
  631.             i = host.rfind(':')
  632.             j = host.rfind(']')
  633.             if i > j:
  634.                 
  635.                 try:
  636.                     port = int(host[i + 1:])
  637.                 except ValueError:
  638.                     if host[i + 1:] == '':
  639.                         port = self.default_port
  640.                     else:
  641.                         raise InvalidURL("nonnumeric port: '%s'" % host[i + 1:])
  642.  
  643.                 host = host[:i]
  644.             else:
  645.                 port = self.default_port
  646.             if host and host[0] == '[' and host[-1] == ']':
  647.                 host = host[1:-1]
  648.             
  649.         self.host = host
  650.         self.port = port
  651.  
  652.     
  653.     def set_debuglevel(self, level):
  654.         self.debuglevel = level
  655.  
  656.     
  657.     def _tunnel(self):
  658.         self._set_hostport(self._tunnel_host, self._tunnel_port)
  659.         self.send('CONNECT %s:%d HTTP/1.0\r\n' % (self.host, self.port))
  660.         for header, value in self._tunnel_headers.iteritems():
  661.             self.send('%s: %s\r\n' % (header, value))
  662.         
  663.         self.send('\r\n')
  664.         response = self.response_class(self.sock, strict = self.strict, method = self._method)
  665.         (version, code, message) = response._read_status()
  666.         if code != 200:
  667.             self.close()
  668.             raise socket.error('Tunnel connection failed: %d %s' % (code, message.strip()))
  669.         while True:
  670.             line = response.fp.readline(_MAXLINE + 1)
  671.             if len(line) > _MAXLINE:
  672.                 raise LineTooLong('header line')
  673.             if not line:
  674.                 break
  675.             if line == '\r\n':
  676.                 break
  677.                 continue
  678.             return None
  679.  
  680.     
  681.     def connect(self):
  682.         '''Connect to the host and port specified in __init__.'''
  683.         self.sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
  684.         if self._tunnel_host:
  685.             self._tunnel()
  686.  
  687.     
  688.     def close(self):
  689.         '''Close the connection to the HTTP server.'''
  690.         if self.sock:
  691.             self.sock.close()
  692.             self.sock = None
  693.         if self._HTTPConnection__response:
  694.             self._HTTPConnection__response.close()
  695.             self._HTTPConnection__response = None
  696.         self._HTTPConnection__state = _CS_IDLE
  697.  
  698.     
  699.     def send(self, data):
  700.         """Send `data' to the server."""
  701.         if self.sock is None:
  702.             if self.auto_open:
  703.                 self.connect()
  704.             else:
  705.                 raise NotConnected()
  706.         if self.debuglevel > 0:
  707.             print 'send:', repr(data)
  708.         blocksize = 8192
  709.         if hasattr(data, 'read') and not isinstance(data, array):
  710.             if self.debuglevel > 0:
  711.                 print 'sendIng a read()able'
  712.             datablock = data.read(blocksize)
  713.             while datablock:
  714.                 self.sock.sendall(datablock)
  715.                 datablock = data.read(blocksize)
  716.         else:
  717.             self.sock.sendall(data)
  718.  
  719.     
  720.     def _output(self, s):
  721.         '''Add a line of output to the current request buffer.
  722.  
  723.         Assumes that the line does *not* end with \\r\\n.
  724.         '''
  725.         self._buffer.append(s)
  726.  
  727.     
  728.     def _send_output(self, message_body = None):
  729.         '''Send the currently buffered request and clear the buffer.
  730.  
  731.         Appends an extra \\r\\n to the buffer.
  732.         A message_body may be specified, to be appended to the request.
  733.         '''
  734.         self._buffer.extend(('', ''))
  735.         msg = '\r\n'.join(self._buffer)
  736.         del self._buffer[:]
  737.         if isinstance(message_body, str):
  738.             msg += message_body
  739.             message_body = None
  740.         self.send(msg)
  741.         if message_body is not None:
  742.             self.send(message_body)
  743.  
  744.     
  745.     def putrequest(self, method, url, skip_host = 0, skip_accept_encoding = 0):
  746.         """Send a request to the server.
  747.  
  748.         `method' specifies an HTTP request method, e.g. 'GET'.
  749.         `url' specifies the object being requested, e.g. '/index.html'.
  750.         `skip_host' if True does not add automatically a 'Host:' header
  751.         `skip_accept_encoding' if True does not add automatically an
  752.            'Accept-Encoding:' header
  753.         """
  754.         if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
  755.             self._HTTPConnection__response = None
  756.         if self._HTTPConnection__state == _CS_IDLE:
  757.             self._HTTPConnection__state = _CS_REQ_STARTED
  758.         else:
  759.             raise CannotSendRequest()
  760.         self._method = None
  761.         if not url:
  762.             url = '/'
  763.         hdr = '%s %s %s' % (method, url, self._http_vsn_str)
  764.         self._output(hdr)
  765.         if self._http_vsn == 11:
  766.             if not skip_host:
  767.                 netloc = ''
  768.                 if url.startswith('http'):
  769.                     (nil, netloc, nil, nil, nil) = urlsplit(url)
  770.                 if netloc:
  771.                     
  772.                     try:
  773.                         netloc_enc = netloc.encode('ascii')
  774.                     except UnicodeEncodeError:
  775.                         netloc_enc = netloc.encode('idna')
  776.  
  777.                     self.putheader('Host', netloc_enc)
  778.                 else:
  779.                     
  780.                     try:
  781.                         host_enc = self.host.encode('ascii')
  782.                     except UnicodeEncodeError:
  783.                         host_enc = self.host.encode('idna')
  784.  
  785.                     if host_enc.find(':') >= 0:
  786.                         host_enc = '[' + host_enc + ']'
  787.                     if self.port == self.default_port:
  788.                         self.putheader('Host', host_enc)
  789.                     else:
  790.                         self.putheader('Host', '%s:%s' % (host_enc, self.port))
  791.             if not skip_accept_encoding:
  792.                 self.putheader('Accept-Encoding', 'identity')
  793.             
  794.  
  795.     
  796.     def putheader(self, header, *values):
  797.         """Send a request header line to the server.
  798.  
  799.         For example: h.putheader('Accept', 'text/html')
  800.         """
  801.         if self._HTTPConnection__state != _CS_REQ_STARTED:
  802.             raise CannotSendHeader()
  803.         hdr = '%s: %s' % (header, '\r\n\t'.join([ str(v) for v in values ]))
  804.         self._output(hdr)
  805.  
  806.     
  807.     def endheaders(self, message_body = None):
  808.         '''Indicate that the last header line has been sent to the server.
  809.  
  810.         This method sends the request to the server.  The optional
  811.         message_body argument can be used to pass a message body
  812.         associated with the request.  The message body will be sent in
  813.         the same packet as the message headers if it is string, otherwise it is
  814.         sent as a separate packet.
  815.         '''
  816.         if self._HTTPConnection__state == _CS_REQ_STARTED:
  817.             self._HTTPConnection__state = _CS_REQ_SENT
  818.         else:
  819.             raise CannotSendHeader()
  820.         None._send_output(message_body)
  821.  
  822.     
  823.     def request(self, method, url, body = None, headers = { }):
  824.         '''Send a complete request to the server.'''
  825.         self._send_request(method, url, body, headers)
  826.  
  827.     
  828.     def _set_content_length(self, body):
  829.         thelen = None
  830.         
  831.         try:
  832.             thelen = str(len(body))
  833.         except TypeError:
  834.             te = None
  835.             
  836.             try:
  837.                 thelen = str(os.fstat(body.fileno()).st_size)
  838.             except (AttributeError, OSError):
  839.                 if self.debuglevel > 0:
  840.                     print 'Cannot stat!!'
  841.                 
  842.             
  843.  
  844.  
  845.         if thelen is not None:
  846.             self.putheader('Content-Length', thelen)
  847.  
  848.     
  849.     def _send_request(self, method, url, body, headers):
  850.         header_names = dict.fromkeys([ k.lower() for k in headers ])
  851.         skips = { }
  852.         if 'host' in header_names:
  853.             skips['skip_host'] = 1
  854.         if 'accept-encoding' in header_names:
  855.             skips['skip_accept_encoding'] = 1
  856.         self.putrequest(method, url, **skips)
  857.         if body is not None and 'content-length' not in header_names:
  858.             self._set_content_length(body)
  859.         for hdr, value in headers.iteritems():
  860.             self.putheader(hdr, value)
  861.         
  862.         self.endheaders(body)
  863.  
  864.     
  865.     def getresponse(self, buffering = False):
  866.         '''Get the response from the server.'''
  867.         if self._HTTPConnection__response and self._HTTPConnection__response.isclosed():
  868.             self._HTTPConnection__response = None
  869.         if self._HTTPConnection__state != _CS_REQ_SENT or self._HTTPConnection__response:
  870.             raise ResponseNotReady()
  871.         args = (self.sock,)
  872.         kwds = {
  873.             'strict': self.strict,
  874.             'method': self._method }
  875.         if self.debuglevel > 0:
  876.             args += (self.debuglevel,)
  877.         if buffering:
  878.             kwds['buffering'] = True
  879.         response = self.response_class(*args, **kwds)
  880.         response.begin()
  881.         if not response.will_close != _UNKNOWN:
  882.             raise AssertionError
  883.         self._HTTPConnection__state = None
  884.         if response.will_close:
  885.             self.close()
  886.         else:
  887.             self._HTTPConnection__response = response
  888.         return response
  889.  
  890.  
  891.  
  892. class HTTP:
  893.     '''Compatibility class with httplib.py from 1.5.'''
  894.     _http_vsn = 10
  895.     _http_vsn_str = 'HTTP/1.0'
  896.     debuglevel = 0
  897.     _connection_class = HTTPConnection
  898.     
  899.     def __init__(self, host = '', port = None, strict = None):
  900.         '''Provide a default host, since the superclass requires one.'''
  901.         if port == 0:
  902.             port = None
  903.         self._setup(self._connection_class(host, port, strict))
  904.  
  905.     
  906.     def _setup(self, conn):
  907.         self._conn = conn
  908.         self.send = conn.send
  909.         self.putrequest = conn.putrequest
  910.         self.putheader = conn.putheader
  911.         self.endheaders = conn.endheaders
  912.         self.set_debuglevel = conn.set_debuglevel
  913.         conn._http_vsn = self._http_vsn
  914.         conn._http_vsn_str = self._http_vsn_str
  915.         self.file = None
  916.  
  917.     
  918.     def connect(self, host = None, port = None):
  919.         """Accept arguments to set the host/port, since the superclass doesn't."""
  920.         if host is not None:
  921.             self._conn._set_hostport(host, port)
  922.         self._conn.connect()
  923.  
  924.     
  925.     def getfile(self):
  926.         """Provide a getfile, since the superclass' does not use this concept."""
  927.         return self.file
  928.  
  929.     
  930.     def getreply(self, buffering = False):
  931.         '''Compat definition since superclass does not define it.
  932.  
  933.         Returns a tuple consisting of:
  934.         - server status code (e.g. \'200\' if all goes well)
  935.         - server "reason" corresponding to status code
  936.         - any RFC822 headers in the response from the server
  937.         '''
  938.         
  939.         try:
  940.             if not buffering:
  941.                 response = self._conn.getresponse()
  942.             else:
  943.                 response = self._conn.getresponse(buffering)
  944.         except BadStatusLine:
  945.             e = None
  946.             self.file = self._conn.sock.makefile('rb', 0)
  947.             self.close()
  948.             self.headers = None
  949.             return (-1, e.line, None)
  950.  
  951.         self.headers = response.msg
  952.         self.file = response.fp
  953.         return (response.status, response.reason, response.msg)
  954.  
  955.     
  956.     def close(self):
  957.         self._conn.close()
  958.         self.file = None
  959.  
  960.  
  961.  
  962. try:
  963.     import ssl
  964. except ImportError:
  965.     pass
  966.  
  967.  
  968. class HTTPSConnection(HTTPConnection):
  969.     '''This class allows communication via SSL.'''
  970.     default_port = HTTPS_PORT
  971.     
  972.     def __init__(self, host, port = None, key_file = None, cert_file = None, strict = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT, source_address = None):
  973.         HTTPConnection.__init__(self, host, port, strict, timeout, source_address)
  974.         self.key_file = key_file
  975.         self.cert_file = cert_file
  976.  
  977.     
  978.     def connect(self):
  979.         '''Connect to a host on a given (SSL) port.'''
  980.         sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
  981.         if self._tunnel_host:
  982.             self.sock = sock
  983.             self._tunnel()
  984.         self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
  985.  
  986.  
  987. __all__.append('HTTPSConnection')
  988.  
  989. class HTTPS(HTTP):
  990.     '''Compatibility with 1.5 httplib interface
  991.  
  992.         Python 1.5.2 did not have an HTTPS class, but it defined an
  993.         interface for sending http requests that is also useful for
  994.         https.
  995.         '''
  996.     _connection_class = HTTPSConnection
  997.     
  998.     def __init__(self, host = '', port = None, key_file = None, cert_file = None, strict = None):
  999.         if port == 0:
  1000.             port = None
  1001.         self._setup(self._connection_class(host, port, key_file, cert_file, strict))
  1002.         self.key_file = key_file
  1003.         self.cert_file = cert_file
  1004.  
  1005.  
  1006.  
  1007. def FakeSocket(sock, sslobj):
  1008.     warnings.warn("FakeSocket is deprecated, and won't be in 3.x.  " + 'Use the result of ssl.wrap_socket() directly instead.', DeprecationWarning, stacklevel = 2)
  1009.     return sslobj
  1010.  
  1011.  
  1012. class HTTPException(Exception):
  1013.     pass
  1014.  
  1015.  
  1016. class NotConnected(HTTPException):
  1017.     pass
  1018.  
  1019.  
  1020. class InvalidURL(HTTPException):
  1021.     pass
  1022.  
  1023.  
  1024. class UnknownProtocol(HTTPException):
  1025.     
  1026.     def __init__(self, version):
  1027.         self.args = (version,)
  1028.         self.version = version
  1029.  
  1030.  
  1031.  
  1032. class UnknownTransferEncoding(HTTPException):
  1033.     pass
  1034.  
  1035.  
  1036. class UnimplementedFileMode(HTTPException):
  1037.     pass
  1038.  
  1039.  
  1040. class IncompleteRead(HTTPException):
  1041.     
  1042.     def __init__(self, partial, expected = None):
  1043.         self.args = (partial,)
  1044.         self.partial = partial
  1045.         self.expected = expected
  1046.  
  1047.     
  1048.     def __repr__(self):
  1049.         if self.expected is not None:
  1050.             e = ', %i more expected' % self.expected
  1051.         else:
  1052.             e = ''
  1053.         return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
  1054.  
  1055.     
  1056.     def __str__(self):
  1057.         return repr(self)
  1058.  
  1059.  
  1060.  
  1061. class ImproperConnectionState(HTTPException):
  1062.     pass
  1063.  
  1064.  
  1065. class CannotSendRequest(ImproperConnectionState):
  1066.     pass
  1067.  
  1068.  
  1069. class CannotSendHeader(ImproperConnectionState):
  1070.     pass
  1071.  
  1072.  
  1073. class ResponseNotReady(ImproperConnectionState):
  1074.     pass
  1075.  
  1076.  
  1077. class BadStatusLine(HTTPException):
  1078.     
  1079.     def __init__(self, line):
  1080.         if not line:
  1081.             line = repr(line)
  1082.         self.args = (line,)
  1083.         self.line = line
  1084.  
  1085.  
  1086.  
  1087. class LineTooLong(HTTPException):
  1088.     
  1089.     def __init__(self, line_type):
  1090.         HTTPException.__init__(self, 'got more than %d bytes when reading %s' % (_MAXLINE, line_type))
  1091.  
  1092.  
  1093. error = HTTPException
  1094.  
  1095. class LineAndFileWrapper:
  1096.     '''A limited file-like object for HTTP/0.9 responses.'''
  1097.     
  1098.     def __init__(self, line, file):
  1099.         self._line = line
  1100.         self._file = file
  1101.         self._line_consumed = 0
  1102.         self._line_offset = 0
  1103.         self._line_left = len(line)
  1104.  
  1105.     
  1106.     def __getattr__(self, attr):
  1107.         return getattr(self._file, attr)
  1108.  
  1109.     
  1110.     def _done(self):
  1111.         self._line_consumed = 1
  1112.         self.read = self._file.read
  1113.         self.readline = self._file.readline
  1114.         self.readlines = self._file.readlines
  1115.  
  1116.     
  1117.     def read(self, amt = None):
  1118.         if self._line_consumed:
  1119.             return self._file.read(amt)
  1120.         if not None._line_left:
  1121.             raise AssertionError
  1122.         if None is None or amt > self._line_left:
  1123.             s = self._line[self._line_offset:]
  1124.             self._done()
  1125.             if amt is None:
  1126.                 return s + self._file.read()
  1127.             return None + self._file.read(amt - len(s))
  1128.         if not amt <= self._line_left:
  1129.             raise AssertionError
  1130.         i = None._line_offset
  1131.         j = i + amt
  1132.         s = self._line[i:j]
  1133.         self._line_offset = j
  1134.         self._line_left -= amt
  1135.         if self._line_left == 0:
  1136.             self._done()
  1137.         return s
  1138.  
  1139.     
  1140.     def readline(self):
  1141.         if self._line_consumed:
  1142.             return self._file.readline()
  1143.         if not None._line_left:
  1144.             raise AssertionError
  1145.         s = None._line[self._line_offset:]
  1146.         self._done()
  1147.         return s
  1148.  
  1149.     
  1150.     def readlines(self, size = None):
  1151.         if self._line_consumed:
  1152.             return self._file.readlines(size)
  1153.         if not None._line_left:
  1154.             raise AssertionError
  1155.         L = [
  1156.             None._line[self._line_offset:]]
  1157.         self._done()
  1158.         if size is None:
  1159.             return L + self._file.readlines()
  1160.         return None + self._file.readlines(size)
  1161.  
  1162.  
  1163.